<!--
 * @Description: 
 * @Author: shizhe
 * @Date: 2022-02-07 11:11:17
 * @LastEditTime: 2022-07-04 12:45:53
 * @LastEditors: shizhe
 * @Reference: 
-->
<template>
  <div id="settlementDialog">
    <h1>基本信息</h1>
    <el-form label-width="130px" class="commonFrom">
      <el-form-item label="合同编号：" style="margin-bottom: 4px !important; margin-right: 500px">
        <el-select
          size="small"
          v-model.trim="settlement.contractId"
          placeholder="请选择合同编号"
          @change="contractChange"
        >
          <el-option
            v-for="item in conOptions"
            :key="item.id"
            :label="item.contractNo"
            :value="item.id"
            :disabled="!item.choose"
          >
            <span>{{ item.contractNo }}</span>
            <span v-if="!item.choose" style="float: right">--虚拟账户待同步!</span>
          </el-option>
        </el-select>
        <!-- <span v-else> {{ settlement.contractNo }}</span> -->
      </el-form-item>
      <el-form-item label="工程名称：" style="margin-bottom: 4px !important">
        {{ settlement.proName || '--' }}
      </el-form-item>
      <el-form-item label="供应商：" style="margin-bottom: 4px !important">
        {{ settlement.providerName || '--' }}
      </el-form-item>
      <el-form-item label="最晚结算日期：" style="margin-bottom: 16px !important">
        <el-date-picker
          size="small"
          style="width: 280px"
          :picker-options="pickerOptions0"
          v-model.trim="settlement.settlementDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <h1>关联订单</h1>
    <div style="margin-top: 20px">
      <el-button size="small" icon="iconfont icon-add" class="commonBtn1" @click="addOrder">添加订单</el-button>
      <el-button size="small" class="commonBtn" @click="removeList">清空</el-button>
    </div>
    <div style="margin: 20px 0">
      <el-table
        :data="settlement.settlementOrderDetailList"
        border
        class="bidding"
        tooltip-effect="light"
        ref="jdjgTable"
        :header-cell-style="{ padding: '0px', background: '#F2F3F7' }"
        :row-class-name="tabRowClassName"
        :summary-method="tableSummary"
        show-summary
        style="width: 100%"
      >
        <el-table-column width="60" align="center" type="index" label="序号">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="订单编号" align="center" prop="orderNo" show-overflow-tooltip> </el-table-column>
        <el-table-column label="货品明细" align="center" prop="orderDetails">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.orderDetails.split(',')" :key="index">
              <el-tooltip effect="light" :content="item" placement="top-start">
                <p class="text_hidde" style="width: 100%">
                  {{ item }}
                </p>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="不含税金额(元)" align="center" prop="noTaxPrice"> </el-table-column>
        <el-table-column label="税金(元)" align="center" prop="taxPrice"> </el-table-column>
        <el-table-column label="价税合计(元)" align="center" prop="totalTaxPrice"> </el-table-column>
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template slot-scope="scope">
            {{ scope.row.orderStatus == 105 ? '待验收' : '已完成' }}
          </template>
        </el-table-column>
        <el-table-column prop="amount5" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" class="ty czBtn" @click="delTableItemBid(scope.$index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <h1>金额和发票</h1>
    <el-form class="commonFrom" label-width="130px" style="margin: 16px 0">
      <el-form-item label="收款金额：" style="margin-bottom: 4px !important">
        {{ settlement.settlementTotalPrice || 0 }}&nbsp;元
      </el-form-item>
      <el-form-item label="发票要求：" style="margin-bottom: 4px !important">
        <span>{{ settlement.invoiceRequirements | invoiceRequirements }}</span>
        <span style="margin-left: 10px">
          {{ settlement.taxRate || '--' }}
          <span v-if="settlement.taxRate">%税率</span>
        </span>
      </el-form-item>
      <el-form-item label="金额调整：" style="margin-bottom: 16px !important; margin-right: 500px">
        <el-input
          style="width: 220px"
          size="small"
          placeholder="减少费用请在数字前输入负号"
          v-model.trim="settlement.adjustPrice"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="调整原因：" style="margin-bottom: 4px !important; width: 100% !important">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          placeholder="请输入调整原因"
          v-model.trim="settlement.adjustReason"
          style="width: 100%"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <h1>联系方式</h1>
    <el-form class="commonFrom" label-width="130px" style="margin: 16px 0">
      <el-form-item label="付款联系人：" style="margin-bottom: 14px !important">
        <el-input
          v-if="enterpriseType == 1"
          style="width: 220px"
          class="no_border"
          disabled
          size="small"
          placeholder="请选择付款联系人"
          v-model.trim="settlement.payer"
        >
          <el-button @click="personnelSelect('payer', '')" slot="append">选择</el-button>
        </el-input>
        <span v-else>{{ settlement.payer || '等待采购商填写联系人' }}</span>
      </el-form-item>
      <el-form-item label="付款联系电话：" style="margin-bottom: 14px !important">
        {{ settlement.payerPhone ? settlement.payerPhone : '--' }}
      </el-form-item>
      <el-form-item label="收款联系人：" style="margin-bottom: 14px !important">
        <el-input
          v-if="enterpriseType == 2"
          style="width: 220px"
          class="no_border"
          disabled
          size="small"
          placeholder="请选择收款联系人"
          v-model.trim="settlement.payee"
        >
          <el-button @click="personnelSelect('payee', '')" slot="append">选择</el-button>
        </el-input>
        <span v-else>{{ settlement.payee || '等待供应商填写联系人' }}</span>
      </el-form-item>
      <el-form-item label="收款联系电话：" style="margin-bottom: 14px !important">
        {{ settlement.payeePhone ? settlement.payeePhone : '--' }}
      </el-form-item>
    </el-form>
    <h1>附件上传</h1>
    <el-button size="small" type="primary" class="commonBtn1" @click="uploadClick" style="margin-top: 20px">
      上传附件
    </el-button>

    <div class="upload-wrap">
      <el-upload
        class="upload-demo"
        :headers="loadHeader"
        multiple
        accept=".doc,.docx,.pdf"
        :action="urlUpload"
        :on-remove="fileRemove"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
        :on-exceed="onExceed"
        :file-list="fileList"
      >
        <template slot="trigger">
          <div ref="biddUpload"></div>
        </template>
      </el-upload>
    </div>
    <h1>结算说明</h1>
    <el-input
      type="textarea"
      :autosize="{ minRows: 3 }"
      placeholder="请输入结算说明"
      v-model.trim="settlement.settlementDescription"
      style="margin: 20px 0"
    >
    </el-input>
    <h1>审核人员</h1>
    <el-button size="small" type="primary" class="commonBtn1 mgn" icon="iconfont icon-add" @click="addReviewer"
      >添加审核人员</el-button
    >
    <el-form class="commonFrom auditfrom" label-width="110px">
      <el-form-item v-for="(item, index) in reviewerList" :key="index" :label="'审核人员' + (index + 1) + '：'">
        <el-input
          style="width: 220px"
          class="no_border"
          disabled
          size="small"
          placeholder="请选择审核人员"
          v-model.trim="item.approverName"
        >
          <el-button @click="personnelSelect('reviewer', index)" slot="append">选择</el-button>
        </el-input>
        <i class="iconfont icon-guanbianniu" @click="colseReviewer(index)"></i>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button size="small" class="commonBtn" @click="closeBtn">取消</el-button>
      <el-button size="small" class="commonBtn1" @click="subBtn">确定</el-button>
    </div>

    <el-dialog
      width="765px"
      :center="true"
      title="选择联系人"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="personVisible"
      v-if="personVisible"
    >
      <personnel-select :type="personType" :index="reviewerIndex" @close="personClose"></personnel-select>
    </el-dialog>

    <el-dialog
      width="1200px"
      :center="true"
      title="选择关联订单"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="addOrderVisiable"
      v-if="addOrderVisiable"
    >
      <associated-order
        @Order="associatedOrder"
        :contractId="settlement.contractId"
        :selectData="settlement.settlementOrderDetailList"
      ></associated-order>
    </el-dialog>
  </div>
</template>

<script>
import PersonnelSelect from '@/components/PersonnelSelect.vue'
import AssociatedOrder from './associatedOrder.vue'
export default {
  name: 'addSettlement',
  data() {
    return {
      // 选择关联订单
      addOrderVisiable: false,
      // 联系人
      reviewerIndex: '',
      personType: '',
      personVisible: false,

      num: 0,
      fileSuccess: true,
      urlUpload: this.GLOBAL.weburl + '/api/file/upload',
      fileList: [],
      enterpriseType: localStorage.getItem('enterpriseType'),
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      settlement: {
        contractId: null,
        contractNo: '',
        invoiceRequirements: null,
        settlementOrderDetailList: [],
        taxRate: null,
        proName: '',
        providerName: '',
        settlementDate: null,
        adjustPrice: null,
        adjustReason: '',
        payee: '',
        payeeId: null,
        payeePhone: '',
        payer: '',
        payerId: null,
        settlementTotalPrice: 0,
        payerPhone: '',
        settlementDescription: '',
        attachUrl: '',
        approveDtoList: []
      },
      conOptions: [],
      reviewerList: [
        {
          approverName: '',
          approverId: ''
        }
      ]
    }
  },
  props: {
    settlementId: {
      type: [String, Number]
    }
  },
  computed: {
    loadHeader() {
      let token = this.common.getCookie('materialsToken')
      const header = {}
      header[this.GLOBAL.tokenName] = token
      return header
    }
  },
  filters: {
    invoiceRequirements(val) {
      const obj = {
        1: '增值税专用发票',
        2: '增值税普通发票',
        3: '普通发票'
      }
      return obj[val]
    }
  },
  components: { PersonnelSelect, AssociatedOrder },
  mounted() {
    if (this.settlementId) {
      this.getDataDetail()
    }
    this.getData()
  },
  methods: {
    // 计算收款金额
    settlementTotalPrice() {
      this.settlement.settlementTotalPrice = 0
      if (this.settlement.settlementOrderDetailList && !this.settlement.settlementOrderDetailList.length) {
        return
      }
      this.settlement.settlementOrderDetailList.forEach(item => {
        this.settlement.settlementTotalPrice += +item.totalTaxPrice
      })
    },
    // 删除文件
    fileRemove(file, files) {
      this.fileList = files
      this.num = this.fileList.length
    },
    // 文件上传前进行文件大小检测
    beforeUpload(file) {
      this.fileSuccess = false
      const isLt = file.size / 1024 / 1024 / 10 <= 1
      if (!isLt) {
        this.$message.error('单个文件大小不能超过10M,请检查文件大小并重新尝试')
      }
      return isLt
    },
    // 文件上传前判断是否超过同时上传文件个数限制
    onExceed() {
      this.$message.error('最多支持同时上传3个文件，请重新上传')
    },
    // 上传成功时的回调
    uploadSuccess(val, e, el) {
      if (e.response.code != 0) {
        this.$message.error(e.response.msg)
        return false
      }
      this.num++
      if (this.num == el.length) {
        this.num = el.length
        this.fileSuccess = true
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.$message.success('上传成功')
      }, 200)
      this.fileList = el
    },
    // 触发上传
    uploadClick() {
      this.$refs.biddUpload.click()
    },
    // 选择合同下拉事件
    contractChange(val) {
      this.conOptions.forEach(item => {
        if (item.id == val) {
          this.settlement.contractNo = item.contractNo
          this.settlement.invoiceRequirements = item.invoiceRequirements
          this.settlement.taxRate = item.taxRate
          this.settlement.proName = item.proName
          this.settlement.providerName = item.providerName
        }
      })
    },
    //选择人员弹窗关闭
    personClose(e) {
      if (this.personType == 'reviewer') {
        this.reviewerList[this.reviewerIndex].approverName = e.userName
        this.reviewerList[this.reviewerIndex].approverId = e.id
      } else if (this.personType == 'payee') {
        // 收款联系人
        this.settlement.payee = e.userName
        this.settlement.payeeId = e.id
        this.settlement.payeePhone = e.phone
      } else if (this.personType == 'payer') {
        // 付款联系人
        this.settlement.payer = e.userName
        this.settlement.payerId = e.id
        this.settlement.payerPhone = e.phone
      }

      this.personVisible = false
    },
    //添加审核人
    addReviewer() {
      if (this.reviewerList.length < 5) {
        this.reviewerList.push({
          approverName: '',
          approverId: ''
        })
      } else {
        this.$message.error('最多添加5位审核人员')
      }
    },
    //删除审核人
    colseReviewer(index) {
      if (this.reviewerList.length > 1) {
        this.$confirm('是否删除审核人?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.reviewerList.splice(index, 1)
          })
          .catch(() => {})
      } else {
        this.$message.error('审核人不能少于一个')
      }
    },
    //选择联系人
    personnelSelect(type, index) {
      this.reviewerIndex = index
      this.personVisible = true
      this.personType = type
    },
    // 添加关联订单
    addOrder() {
      if (!this.settlement.contractId) {
        this.$message.error('请选择合同编号')
        return
      }
      this.addOrderVisiable = true
    },
    // 选择关联订单抛出
    associatedOrder(e) {
      console.log(e)
      this.addOrderVisiable = false
      e && (this.settlement.settlementOrderDetailList = [...this.settlement.settlementOrderDetailList, ...e])
      this.settlementTotalPrice()
    },
    // 表格合计自定义方法
    tableSummary(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 6) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    // 删除关联订单表格中的某一项
    delTableItemBid(index) {
      if (this.settlement.settlementOrderDetailList[index].id) {
        this.$https({
          method: 'post',
          url: '/settlement/deleteSettlementOrderDetail?id=' + this.settlement.settlementOrderDetailList[index].id
        })
          .then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功')
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
      this.settlement.settlementOrderDetailList.splice(index, 1)
      this.settlementTotalPrice()
    },
    // 清空关联订单表格
    removeList() {
      this.$confirm('是否清空关联订单表格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.settlement.settlementOrderDetailList = []
        this.settlementTotalPrice()
      })
    },
    // 获取合同下拉
    getData() {
      this.$https({
        method: 'post',
        url: '/contract/getContractProNameList'
      })
        .then(res => {
          if (res.code == 0) {
            this.conOptions = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 获取结算单详情
    getDataDetail() {
      this.$https({
        method: 'post',
        url: '/settlement/settlementDetails?id=' + this.settlementId
      })
        .then(res => {
          // console.log(res)
          if (res.code == 0) {
            this.settlement = res.data
            this.settlement.settlementOrderDetailList = res.data.settlementOrderDetailList
            this.fileList = JSON.parse(res.data.attachUrl)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    closeBtn() {
      this.$emit('close')
    },
    updateSettlement() {
      this.$https({
        method: 'post',
        url: '/settlement/updSettlement',
        data: this.settlement
      })
        .then(res => {
          if (res.code == 0) {
            // this.$emit('close', 'init')
            this.$emit('close', 'init')
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    subBtn() {
      this.settlement.adjustPrice = this.settlement.adjustPrice || 0
      // 过滤出id存在的审核人
      this.settlement.approveDtoList = this.reviewerList.filter(item => {
        return item.approverId
      })
      if (!this.fileSuccess) {
        this.$message.error('请等待文件上传完毕')
        return false
      } else {
        if (this.fileList.length) {
          this.settlement.attachUrl = JSON.stringify(this.fileList)
        }
      }
      if (!this.settlement.contractId) {
        this.$message.error('请选择合同编号')
        return
      } else if (!this.settlement.settlementDate) {
        this.$message.error('请选择结算日期')
        return
      } else if (!this.settlement.settlementOrderDetailList.length) {
        this.$message.error('请选择关联订单')
        return
      } else if (this.settlement.adjustPrice && !/^(-|\+)?\d+$/.test(this.settlement.adjustPrice)) {
        this.$message.error('请输入格式正确的金额')
        this.settlement.adjustPrice = ''
        return
      } else if (
        this.settlement.adjustPrice &&
        this.settlement.adjustPrice.substr(0, 1) == '-' &&
        Math.abs(this.settlement.adjustPrice) > parseInt(this.settlement.settlementTotalPrice)
          ? true
          : false
      ) {
        this.$message.error('请输入正确的调整金额')
        this.settlement.adjustPrice = ''
        return
      } else if (this.settlement.adjustPrice && !this.settlement.adjustReason) {
        this.$message.error('请输入调整原因')
        return
      } else if (localStorage.getItem('enterpriseType') == 1 && !this.settlement.payerId) {
        this.$message.error('请选择付款联系人')
        return
      } else if (localStorage.getItem('enterpriseType') == 2 && !this.settlement.payee) {
        this.$message.error('请选择收款联系人')
        return
      } else if (!this.settlement.approveDtoList.length) {
        this.$message.error('请选择审核人')
        return
      }
      // 为审核人添加审核顺序
      this.settlement.approveDtoList.forEach((item, index) => {
        this.$set(item, 'approveSort', index)
      })
      if (this.settlementId) {
        this.updateSettlement()
        return
      }
      this.$https({
        method: 'post',
        url: '/settlement/addSettlement',
        data: this.settlement
      })
        .then(res => {
          if (res.code == 0) {
            this.$emit('close', 'init')
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    tabRowClassName({ row, rowIndex }) {
      let index = rowIndex + 1
      if (index % 2 == 0) {
        return 'warning-row'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.commonFrom {
  margin-top: 7px;
  width: 88%;
  .el-form-item {
    width: 40% !important;
    margin-bottom: 7px !important;
  }
  .form-item {
    width: 100% !important;
    /deep/.el-form-item__content {
      display: flex;
    }
    .el-input {
      width: 260px;
    }
  }

  .performance_text {
    color: #999;
    font-size: 14px;
  }
  .icon-guanbianniu {
    font-size: 16px;
    cursor: pointer;
    margin-left: 10px;
  }
  .icon-guanbianniu:hover {
    color: #fa7355;
  }
}
h1 {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #fa7355;
  span {
    font-weight: normal;
    color: #999;
  }
}
.ty {
  color: #ff3d3d;
}
.mgn {
  margin-top: 20px;
}
.auditfrom {
  margin: 16px 0 0;
  .el-form-item {
    width: 43% !important;
    margin-bottom: 16px !important;
  }
}
.footer {
  .commonBtn,
  .commonBtn1 {
    width: 130px;
  }
  text-align: center;
  margin-top: 20px;
}
.upload-wrap {
  /deep/.el-upload {
    display: none;
  }
  /deep/.el-upload-list {
    display: flex;
    align-items: center;
    width: 600px;
    flex-wrap: wrap;
    margin-bottom: 20px;
    .el-upload-list__item {
      width: 260px;
      margin: 20px 30px 0 0;
      background: #f0f1f2;
      border: 1px solid #d6d6d6;
    }
    .el-icon-close {
      &:hover {
        color: #fa7355;
      }
    }
  }
}
</style>
